import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_ghz/api/user.dart';
import 'package:flutter_enjoy_plus_ghz/utils/PrompAction.dart';
import 'package:flutter_enjoy_plus_ghz/utils/TokenManager.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _phoneController = TextEditingController(); // 手机号
  TextEditingController _codeController = TextEditingController(); // 验证码

  int _countDown = 60;
  Timer? timer;
  // 开始倒计时
  void beginCount() {
    // 开始倒计时
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countDown == 0) {
        // 此时应该结束
        _countDown = 60;
        timer.cancel();
      } else {
        _countDown--;
      }
      setState(() {});
    });
  }

  // 发送验证码
  void _sendCode() async {
    if (_countDown == 60) {
      if (_phoneController.text.isEmpty) {
        return PromptAction.showError("手机号不能为空");
      }
      RegExp reg = RegExp(r'^1[3-9]\d{9}$'); // flutter正则表达式
      if (!reg.hasMatch(_phoneController.text)) {
        return PromptAction.showError("手机号格式不正确");
      }
      setState(() {
        _countDown--;
      });
      // 发送验证码
      var res = await sendCodeAPI({"mobile": _phoneController.text});
      Future.delayed(Duration(seconds: 1), () {
        _codeController.text = res["code"];
      });
      beginCount();
    }

    // 正则表达式
    // /^1[3-9]\d{9}$/
  }

  void _login() async {
    // _phoneController.text;
    // _codeController.text;
    if (_phoneController.text.isEmpty || _codeController.text.isEmpty) {
      PromptAction.showError("手机号和验证码不能为空");
      return;
    }
    RegExp pReg = RegExp(r'^1[3-9]\d{9}$'); // 手机号正则
    RegExp cReg = RegExp(r'^\d{6}$'); // 验证码正则
    if (!pReg.hasMatch(_phoneController.text) ||
        !cReg.hasMatch(_codeController.text)) {
      PromptAction.showError("手机号和验证码格式不正确");
      return;
    }
    // 发送接口
    var res = await loginAPI(
        {"mobile": _phoneController.text, "code": _codeController.text});
    tokenManager.setToken(res["token"], refreshToken: res["refreshToken"]);
    timer?.cancel();
    Navigator.pop(context);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer?.cancel(); // 清理定时器
  }

  Widget getTimerShow() {
    if (_countDown < 60) {
      return Text(
        '还剩${_countDown}秒',
        style: const TextStyle(color: Colors.grey),
      );
    }
    return const Text("发送验证码");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // 发送验证码
                    // beginCount();
                    _sendCode();
                  },
                  child: getTimerShow(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // 登录方法
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
